// src/utils/websocket.js
let socket = null;

export function connectWebSocket(url, onMessage, onOpen, onClose, onError) {
  if ('WebSocket' in window) {
    socket = new WebSocket(url);

    socket.onopen = () => {
      console.log('WebSocket connection opened');
      if (onOpen) onOpen();
    };

    socket.onmessage = (event) => {
      console.log('Received message:', event.data);
      if (onMessage) onMessage(event.data);
    };

    socket.onclose = () => {
      console.log('WebSocket connection closed');
      if (onClose) onClose();
    };

    socket.onerror = (error) => {
      console.error('WebSocket error:', error);
      if (onError) onError(error);
    };
  } else {
    console.error('Your browser does not support WebSocket.');
  }
}

export function sendMessage(message) {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(message);
  } else {
    console.warn('WebSocket is not open. Message not sent:', message);
  }
}

export function closeWebSocket() {
  if (socket) {
    socket.close();
  }
}
